package com.syni.mdd.yhd.common.all.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.log4j.Log4j2;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @className ThirdInterfaceUtils
 * @description 第三方接口调用工具类
 * @Author cfx
 * @DATE 2019/5/6 12:53
 * @VERSION 1.0
 **/
@Log4j2
public class ThirdInterfaceUtils {

    final static int retryNum = 5;

    public static String findCityByPhone(String phone){
        String ret = "";
        AtomicInteger atomicInteger = new AtomicInteger();
        String url = "http://mobsec-dianhua.baidu.com/dianhua_api/open/location";
        Map<String,Object> paramsMap = new HashMap<>();
        paramsMap.put("tel",phone);
        while (atomicInteger.getAndIncrement() < retryNum) {
            try {
                String responseBody = RestTemplateUtils.getForEntity(url, paramsMap);
                if (StringUtils.isNotBlank(responseBody)) {
                    Map<String, Object> responseBodyMap = JSON.parseObject(responseBody);
                    System.out.println(responseBodyMap);
                    responseBodyMap = (Map<String, Object>) responseBodyMap.get("response");
                    responseBodyMap = (Map<String, Object>) responseBodyMap.get(phone);
                    responseBodyMap = (Map<String, Object>) responseBodyMap.get("detail");
                    JSONArray jsonArray = (JSONArray) responseBodyMap.get("area");
                    if (jsonArray.size() > 0) {
                        responseBodyMap = jsonArray.getJSONObject(0);
                        ret = responseBodyMap.get("city").toString();
                        break;
                    }
                }
            } catch (Exception e) {
                log.error(e.getMessage(),e);
            }
        }
        return ret;
    }
}
